﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;

namespace ZBZH_Manage_Order.Controllers.MerchantsSettings
{
    public class Order_ShelvesController : Controller
    {
        //
        // GET: /Order_Shelves/
        ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取当前操作员拥有商品分类
        /// </summary>
        /// <returns></returns>
        public ActionResult getOrderType(string MerID)
        {
            try
            {
                List<Model.Order_DishesType_T> list_Order_DishesType = new List<Model.Order_DishesType_T>();//定义商品分类设置
                list_Order_DishesType = OrderType(MerID);
                if (list_Order_DishesType != null)
                {
                    return Json(list_Order_DishesType, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("加载异常！");
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 商品分类信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        public List<Model.Order_DishesType_T> OrderType(string MerID)
        {
            List<Model.Order_DishesType_T> list_Order_DishesType = new List<Model.Order_DishesType_T>();//定义商品分类设置
            string result = service.GetOrder_DishesType(MerID, "", 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    foreach (JToken item in jieguo)
                    {
                        Model.Order_DishesType_T m = new Model.Order_DishesType_T();
                        m.DishesTypeID = item["DishesTypeID"].ToString();
                        m.DishesTypeName = item["DishesTypeName"].ToString();
                        list_Order_DishesType.Add(m);
                    }
                }
            }
            return list_Order_DishesType;
        }

        /// <summary>
        /// 获取商户的上架信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        public ActionResult getgrid(string MerID, JqGridParam jqgridparam)
        {
            try
            {
                Page<Models.View_Order_Shelves_More> page = new Page<Models.View_Order_Shelves_More>();//分页类定义
                List<Models.View_Order_Shelves_More> list = new List<Models.View_Order_Shelves_More>();
                list = GetAllShelves(MerID,jqgridparam);
                if (list.Count > 0)
                {
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = list.Count.ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = "0",
                        rows = list
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取对应商户的上架信息
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        public List<Models.View_Order_Shelves_More> GetAllShelves(string MerID, JqGridParam jqgridparam)
        {
            List<Models.View_Order_Shelves_More> list_More = new List<Models.View_Order_Shelves_More>();//获取上架信息
            string result = service.GetOrder_Shelves(jqgridparam.page,jqgridparam.rows,MerID, "", 1);
            JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
            string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
            if (bs == "1")//返回结果正常
            {
                IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                if (jieguo.Count > 0)
                {
                    foreach (JToken item in jieguo)
                    {
                        List<Models.Order_Dishes_T_More> Dishes = new List<Models.Order_Dishes_T_More>();
                        Models.View_Order_Shelves_More m = new Models.View_Order_Shelves_More();
                        m.SheID = int.Parse(item["SheID"].ToString());
                        m.DishesID = item["DishesID"].ToString();
                        m.MerID = item["MerID"].ToString();
                        m.SheName = item["SheName"].ToString();
                        m.MerName = item["MerName"].ToString();
                        m.DishesNub = item["DishesNub"].ToString();
                        m.SheDateB = int.Parse(item["SheDateB"].ToString());
                        m.SheDateE = int.Parse(item["SheDateE"].ToString());
                        string SheDateB = item["SheDateB"].ToString();
                        SheDateB = SheDateB.Substring(0, 4) + "-" + SheDateB.Substring(4, 2) + "-" + SheDateB.Substring(6, 2);
                        m.Str_SheDateB = SheDateB;
                        string SheDateE = item["SheDateE"].ToString();
                        SheDateE = SheDateE.Substring(0, 4) + "-" + SheDateE.Substring(4, 2) + "-" + SheDateE.Substring(6, 2);
                        m.Str_SheDateE = SheDateE;
                        string SheTimeB = item["SheTimeB"].ToString();
                        SheTimeB = SheTimeB.Substring(0, 2) + ":" + SheTimeB.Substring(2, 2);
                        m.SheTimeB = SheTimeB;
                        string SheTimeE = item["SheTimeE"].ToString();
                        SheTimeE = SheTimeE.Substring(0, 2) + ":" + SheTimeE.Substring(2, 2);
                        m.SheTimeE = SheTimeE;
                        m.MaDay = int.Parse(item["MaDay"].ToString());
                        string MaTime = item["MaTime"].ToString();
                        if (MaTime == "0|0")
                        {
                            m.MaTime = "不允许预约";
                        }
                        else
                        {
                            m.MaTime = MaTime.Substring(0, 2) + ":" + MaTime.Substring(2, 5) + ":" + MaTime.Substring(7, 2);
                        }
                        m.BZ = item["BZ"].ToString();
                        IList<JToken> jieguo2 = item["DisheList"].Children().ToList();//解析返回的结果
                        Dishes = ParseClass<Models.Order_Dishes_T_More>.JsonList(jieguo2);//解析返回的结果
                        m.DisheList = Dishes;
                        list_More.Add(m);
                    }
                }
                return list_More;
            }
            else
            {
                return list_More;
            }
        }

        /// <summary>
        /// 绑定商户ID和上架ID获取上架商品信息
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="SheID">上架ID</param>
        /// <returns></returns>
        public ActionResult GetShelves(string MerID, int SheID, JqGridParam jqgridparam)
        {
            try
            {
                Page<Models.Order_Dishes_T_More> page = new Page<Models.Order_Dishes_T_More>();
                List<Models.Order_Dishes_T_More> ls = GetAllShelvesDishes(MerID, SheID,jqgridparam);
                List<Models.Order_Dishes_T_More> newuc = new List<Models.Order_Dishes_T_More>();//定义一个新的对象，用于保存查询后的实体类列表
                for (int i = 0; i < ls.Count; i++)
                {
                    //newuc.Add(ls[i]);
                    if (ls[i].DishesNub > 0)
                    {
                        newuc.Add(ls[i]);
                    }
                }
                jqgridparam.records = newuc.Count;//查询的数据总数
                var data = new
                {
                    total = newuc.Count,
                    rows = page.FindListPage(newuc, ref jqgridparam)//返回当前页的数据
                };
                return Json(data);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 获取商户ID和上架ID获取上架商品信息
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="SheID">上架ID</param>
        /// <returns></returns>
        public List<Models.Order_Dishes_T_More> GetAllShelvesDishes(string MerID, int SheID, JqGridParam jqgridparam)
        {
            List<Model.Order_DishesType_T> DishesType_list = new List<Model.Order_DishesType_T>();//商品分类
            List<Models.View_Order_Shelves_More> AllDishes_list = new List<Models.View_Order_Shelves_More>();//商品list
            AllDishes_list = GetAllShelves(MerID,jqgridparam);
            List<Models.Order_Dishes_T_More> Dishes_list = new List<Models.Order_Dishes_T_More>();//商品list
            List<Model.View_Order_Dishes> List_AllDishes = new List<View_Order_Dishes>();//查询该商户的所有商品
            List_AllDishes = GetAllDishes(MerID);//查询该商户的所有商品
            List<Models.Order_Dishes_T_More> zcdlist = new List<Order_Dishes_T_More>();
            foreach (Model.View_Order_Dishes All_D_item in List_AllDishes)//根据所有商品查看对应的上架信息
            {
                List<Models.View_Order_Shelves_More> DCDls = (from u in AllDishes_list where u.SheID == SheID select u).ToList();//查询对应上架信息
                if (DCDls.Count > 0)//如果没有上架信息
                {
                    Dishes_list = DCDls[0].DisheList;//上架的商品信息
                    List<Models.Order_Dishes_T_More> D = (from u in Dishes_list where u.DishesID == All_D_item.DishesID select u).ToList();//在上架信息中查找商品信息
                    if (D.Count > 0)//如果是已上架信息
                    {
                        zcdlist.Add(D[0]);//上架的商品信息
                    }
                    else//如果不是上架信息
                    {
                        Models.Order_Dishes_T_More M = new Order_Dishes_T_More();//上架信息
                        M.DishesID = All_D_item.DishesID;
                        M.DishesNmae = All_D_item.DishesNmae;
                        M.DishesTypeID = All_D_item.DishesTypeID;
                        M.DishesTypeName = All_D_item.DishesTypeName;
                        M.DishesNub = 0;//上架数量为零
                        zcdlist.Add(M);
                    }
                }
                else
                {
                    Models.Order_Dishes_T_More M = new Order_Dishes_T_More();//上架信息
                    M.DishesID = All_D_item.DishesID;
                    M.DishesNmae = All_D_item.DishesNmae;
                    M.DishesTypeID = All_D_item.DishesTypeID;
                    M.DishesTypeName = All_D_item.DishesTypeName;
                    M.DishesNub = 0;//上架数量为零
                    zcdlist.Add(M);
                }
            }
            return zcdlist;
        }

        /// <summary>
        /// 获取对应商户的所有商品
        /// </summary>
        /// <param name="MerID"></param>
        /// <returns></returns>
        public List<Model.View_Order_Dishes> GetAllDishes(string MerID)
        {
            Log.Debug("获取对应商户的所有商品",MerID);
            try
            {
                List<Model.View_Order_Dishes> list = new List<Model.View_Order_Dishes>();
                string result = service.GetOrder_Dishes(MerID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            // List<Model.Sys_Component_T> list_com = new List<Model.Sys_Component_T>();
                            List<Model.View_Order_Dishes> list_Dishes = new List<Model.View_Order_Dishes>();
                            Model.View_Order_Dishes m = new Model.View_Order_Dishes();
                            m.DishesID = item["DishesID"].ToString();
                            m.DishesNmae = item["DishesNmae"].ToString();
                            m.MerID = item["MerID"].ToString();
                            m.MerName = item["MerName"].ToString();
                            m.DishesTypeID = item["DishesTypeID"].ToString();
                            m.DishesEnableInt = int.Parse(item["DishesEnableInt"].ToString());
                            m.DishesIsInt = int.Parse(item["DishesIsInt"].ToString());
                            m.DishesMon = int.Parse(item["DishesMon"].ToString());
                            m.DishesPay = int.Parse(item["DishesPay"].ToString());
                            m.DishesVol = int.Parse(item["DishesVol"].ToString());
                            m.DishesTxt = item["DishesTxt"].ToString();
                            m.DishesPic = item["DishesPic"].ToString();
                            m.DishesEvaNun = int.Parse(item["DishesEvaNun"].ToString());
                            m.DishesEvaTxt = int.Parse(item["DishesEvaTxt"].ToString());
                            m.DishesEvaX = int.Parse(item["DishesEvaX"].ToString());
                            m.DishesGood = int.Parse(item["DishesGood"].ToString());
                            m.DishesTypeState = int.Parse(item["DishesTypeState"].ToString());
                            m.IntBZ = item["IntBZ"].ToString();
                            m.DishesTypeName = item["DishesTypeName"].ToString();
                            list.Add(m);
                        }
                    }
                    return list;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                Log.Debug("异常", ex.ToString());
                throw;
            }
           
        }

        /// <summary>
        /// 获取系统的增删查改的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getPower()
        {
            try
            {
                string[] PowerS = null;
                Models.ControlPower RetPower = new Models.ControlPower();
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];
                if (user != null)
                {
                    PowerS = user.RolePower.Split(',');//权限码
                    //拼接增删查改的权限
                    foreach (string pow in PowerS)
                    {
                        if (pow == "009006002")
                        {
                            RetPower.Add = 1;
                        }
                        else if (pow == "009006003")
                        {
                            RetPower.Dell = 1;
                        }
                        else if (pow == "009006004")
                        { RetPower.Edit = 1; }
                    }
                }
                else
                {
                    return RedirectToAction("LoginPage", "Login");  //czx，修改为登录者的Session异常时，直接跳转到登录页面
                }

                return Json(RetPower);
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 获取当前操作员拥有商户的权限
        /// </summary>
        /// <returns></returns>
        public ActionResult getMer(JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_Mer_T> page = new Page<Model.Order_Mer_T>();
                List<Model.Order_Mer_T> list = new List<Model.Order_Mer_T>();//定义商品分类设置
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx，修改为登录者的Session异常时，直接跳转到登录页面
                }

                string result = service.GetMer(user.OperID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_Mer_T m = new Model.Order_Mer_T();
                            m.MerID = item["MerID"].ToString();
                            m.MerName = item["MerName"].ToString();
                            m.MerAdr = item["MerAdr"].ToString();
                            m.MerCall = item["MerCall"].ToString();
                            m.MerTxt = item["MerTxt"].ToString();
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                return Json(searcho["Msg"].ToString());
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 更新商品上架信息
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="SaveShelves"></param>
        /// <returns></returns>
        public ActionResult UpdateOrder_Dishes(int Tag, SaveShelves SaveShelves)
        {
            try
            {
                string DishesID = "";//拼接上架商品ID
                string DishesNub = "";//拼接上架商品数量
                if (SaveShelves.SheDataGrid != null & SaveShelves.SheDataGrid != "")
                {
                    //解析上架商品名称和ID
                    List<Models.Order_Dishes_T_More> SheList = PublicMethod.JsonHelper.JonsToList<Models.Order_Dishes_T_More>(SaveShelves.SheDataGrid);
                    //拼接上架商品
                    foreach (Models.Order_Dishes_T_More item in SheList)
                    {
                        if (item.DishesNub > 0)//如果上架数量为0说明不上架
                        {
                            DishesID = DishesID + "," + item.DishesID;
                            DishesNub = DishesNub + "," + item.DishesNub;
                        }
                    }
                    //当拼接上架商品不为空时要去掉对一个逗号
                    if (DishesID != "" & DishesNub != "")
                    {
                        DishesID = DishesID.Remove(0, 1);
                        DishesNub = DishesNub.Remove(0, 1);
                    }
                    #region 给上架信息赋值
                    Model.Order_Shelves_T NewShelves = new Order_Shelves_T();
                    if (SaveShelves.SheID == null)
                    {
                        NewShelves.SheID = 0;
                    }
                    else
                    {
                        NewShelves.SheID = int.Parse(SaveShelves.SheID);
                    }
                    NewShelves.MerID = SaveShelves.MerID;
                    NewShelves.SheName = SaveShelves.SheName;
                    NewShelves.DishesID = DishesID;
                    NewShelves.DishesNub = DishesNub;
                    NewShelves.SheDateB = int.Parse(SaveShelves.SheDateB.Replace("-", ""));
                    NewShelves.SheDateE = int.Parse(SaveShelves.SheDateE.Replace("-", ""));
                    NewShelves.SheTimeB = SaveShelves.SheTimeB.Replace(":", "");
                    NewShelves.SheTimeE = SaveShelves.SheTimeE.Replace(":", "");
                    NewShelves.MaDay = SaveShelves.MaDay;
                    NewShelves.MaTime = SaveShelves.MaTime.Replace(":", "");
                    NewShelves.BZ = SaveShelves.BZ;
                    #endregion

                    string result = "";
                    string tojson =NewShelves.ToJson();
                    Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];//获取操作员

                    if (user == null)
                    {
                        return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                    }

                    result = service.SetOrder_Shelves(user.OperID, tojson, Tag, GetYZM._YZM, 1);//设置上架信息
                    JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                    string bs = searcho["BS"].ToString();//判断结果
                    if (bs == "1")
                    {
                        return Content(bs);
                    }
                    else
                    {
                        return Content(searcho["Msg"].ToString());
                    }
                }
                else if (Tag == 3)
                {
                    #region 给上架信息赋值
                    Model.Order_Shelves_T NewShelves = new Order_Shelves_T();
                    if (SaveShelves.SheID == null)
                    {
                        NewShelves.SheID = 0;
                    }
                    else
                    {
                        NewShelves.SheID = int.Parse(SaveShelves.SheID);
                    }
                    NewShelves.MerID = SaveShelves.MerID;
                    NewShelves.SheName = SaveShelves.SheName;
                    NewShelves.DishesID = DishesID;
                    NewShelves.DishesNub = DishesNub;
                    NewShelves.SheDateB = int.Parse(SaveShelves.SheDateB.Replace("-", ""));
                    NewShelves.SheDateE = int.Parse(SaveShelves.SheDateE.Replace("-", ""));
                    NewShelves.SheTimeB = SaveShelves.SheTimeB.Replace(":", "");
                    NewShelves.SheTimeE = SaveShelves.SheTimeE.Replace(":", "");
                    NewShelves.MaDay = SaveShelves.MaDay;
                    NewShelves.MaTime = SaveShelves.MaTime.Replace(":", "");
                    NewShelves.BZ = SaveShelves.BZ;
                    #endregion
                    string result = "";
                    Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];//获取操作员

                    if (user == null)
                    {
                        return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                    }

                    result = service.SetOrder_Shelves(user.OperID, NewShelves.ToJson(), Tag, GetYZM._YZM, 1);//设置上架信息
                    JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                    string bs = searcho["BS"].ToString();//判断结果
                    if (bs == "1")
                    {
                        return Content(bs);
                    }
                    else
                    {
                        return Content(searcho["Msg"].ToString());
                    }
                }
                else
                { return Content("操作异常"); }
            }
            catch (Exception ex)
            {
                return Content("操作异常：" + ex + "请联系管理员解决");
            }
        }



        #region 查询上架商品信息
        /// <summary>
        /// 查询上架商品信息
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="SheID">上架ID</param>
        /// <param name="IsShelves">是否上架</param>
        /// <param name="DishesType">商品类型</param>
        /// <param name="jqgridparam"></param>
        /// <returns></returns>
        /// 
        public ActionResult searchShelves(string MerID, int SheID, string IsShelves, string DishesType, JqGridParam jqgridparam)
        {
            try
            {
                Page<Models.Order_Dishes_T_More> page = new Page<Models.Order_Dishes_T_More>();
                List<Models.Order_Dishes_T_More> ls = GetAllShelvesDishes(MerID, SheID,jqgridparam);
                List<Models.Order_Dishes_T_More> newuc = new List<Models.Order_Dishes_T_More>();//定义一个新的对象，用于保存查询后的实体类列表
                for (int i = 0; i < ls.Count; i++)
                {
                    if (DishesType != "0" && IsShelves == "1")
                    {
                        if (ls[i].DishesTypeID.IndexOf(DishesType) > -1 && ls[i].DishesNub > 0)
                        {
                            newuc.Add(ls[i]);
                        }
                    }
                    else if (DishesType != "0" && IsShelves == "2")
                    {
                        if (ls[i].DishesTypeID.IndexOf(DishesType) > -1 && ls[i].DishesNub == 0)
                        {
                            newuc.Add(ls[i]);
                        }
                    }
                    else if (DishesType != "0" && IsShelves == "3")
                    {
                        if (ls[i].DishesTypeID.IndexOf(DishesType) > -1)
                        {
                            newuc.Add(ls[i]);
                        }
                    }
                    else if (DishesType == "0" && IsShelves == "1")
                    {
                        if (ls[i].DishesNub > 0)
                        {
                            newuc.Add(ls[i]);
                        }
                    }
                    else if (DishesType == "0" && IsShelves == "2")
                    {
                        if (ls[i].DishesNub == 0)
                        {
                            newuc.Add(ls[i]);
                        }
                    }
                    else if (DishesType == "0" && IsShelves == "3")
                    {
                        newuc.Add(ls[i]);
                    }
                }
                jqgridparam.records = newuc.Count;//查询的数据总数
                var data = new
                {
                    total = newuc.Count,
                    rows = page.FindListPage(newuc, ref jqgridparam)//返回当前页的数据 
                };
                return Json(data);
            }
            catch (Exception) { return null; }
        }
        #endregion

        /// <summary>
        /// 定义从界面返回的商品上架信息
        /// </summary>
        public class SaveShelves
        {
            public string SheID { get; set; }
            public string MerID { get; set; } //商户id
            public string SheName { get; set; } //描述
            public string SheDateB { get; set; } //上架日期
            public string SheDateE { get; set; } //下架日期
            public string SheTimeB { get; set; } //每天运营开始时间
            public string SheTimeE { get; set; } //每天停止运营时间
            public int MaDay { get; set; }  //允许预约天数
            public string MaTime { get; set; } //允许预约时间范围
            public string BZ { get; set; }  //备注
            public string SheDataGrid { get; set; } //shang
            //List<Models.Order_Dishes_T_More> SheDataGrid { get; set; }
        }
    }
}
